package top.iuna.jxls.core.view;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.web.servlet.view.AbstractView;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import top.iuna.jxls.core.exception.BusinessException;
import top.iuna.jxls.core.util.FileNameKit;

/**
 * Spring View 之 简易JxlsView<br>
 * 一个sheet最多65535行,但是如果一次性导出的话,鉴于性能/时间等建议不要超过5k行数据量
 * 
 * @author Cheney.Sun
 * @time 2018-04-07
 */

@Setter
@Getter
@Slf4j
public class SimpleJxlsView extends AbstractView {

  /**
   * 模板路径
   */
  private String templateFilePath;
  /**
   * 模板路径是否是相对路径,默认是
   */
  private boolean isRelativePath = true;
  /**
   * 导出文件的目标文件名(不包括后缀名)
   */
  private String targetFileName;


  public SimpleJxlsView() {
    super();
    initViewSettings();
  }

  public SimpleJxlsView(String templateFilePath, String targetFileName) {
    super();
    initViewSettings();
    this.templateFilePath = templateFilePath;
    this.targetFileName = targetFileName;
  }

  public SimpleJxlsView(String templateFilePath, boolean isRelativePath, String targetFileName) {
    super();
    initViewSettings();
    this.templateFilePath = templateFilePath;
    this.isRelativePath = isRelativePath;
    this.targetFileName = targetFileName;
  }



  @Override
  protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
      HttpServletResponse response) throws Exception {
    try (
        InputStream inStream =
            isRelativePath ? this.getClass().getClassLoader().getResourceAsStream(this.templateFilePath)
                : new FileInputStream(this.templateFilePath);
        ServletOutputStream outStream = response.getOutputStream()) {
      if (null == inStream) {
        throw new BusinessException("Template 文件路径有误!");
      }

      String encodedFileName = FileNameKit.httpEncode(request, this.targetFileName) + "."
          + StringUtils.substringAfterLast(this.templateFilePath, ".");
      response.setContentType(this.getContentType());
      response.setHeader("content-disposition",
          "attachment;filename=" + encodedFileName + "; filename*=utf-8''" + encodedFileName);

      // setUseFastFormulaProcessor(false),默认时为true,防止函数统计可能会出错
      JxlsHelper.getInstance().setUseFastFormulaProcessor(false).processTemplate(inStream, outStream,
          new Context(model));
    } catch (Exception e) {
      log.error("SimpleJxlsView#renderMergedOutputModel error:", e);
    }
  }

  private void initViewSettings() {
    this.setContentType("application/vnd.ms-excel;charset=UTF-8");
  }



}
